package and.example.util;

import java.util.Map;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

public class Utils {

	public static Bitmap createScaledBitmapKeepingAspectRatio(Bitmap bitmap,
			int maxSide) {

		if (bitmap != null) {

			int orgHeight = bitmap.getHeight();
			int orgWidth = bitmap.getWidth();

			// scale to no longer any either side than 75px
			int scaledWidth = (orgWidth >= orgHeight) ? maxSide
					: (int) ((float) maxSide * ((float) orgWidth / (float) orgHeight));
			int scaledHeight = (orgHeight >= orgWidth) ? maxSide
					: (int) ((float) maxSide * ((float) orgHeight / (float) orgWidth));

			// create the scaled bitmap
			Bitmap scaledGalleryPic = Bitmap.createScaledBitmap(bitmap,
					scaledWidth, scaledHeight, true);
			return scaledGalleryPic;
		}

		return null;
	}

	public static int calculateInSampleSize(Options options, int reqW, int reqH) {

		int h = options.outHeight;
		int w = options.outWidth;
		int inSampleSize = 1;

		if (w > reqW || h > reqH) {

			int ratioH = Math.round((float) h / (float) reqH);
			int ratioW = Math.round((float) w / (float) reqW);

			inSampleSize = ratioH < ratioW ? ratioH : ratioW;
		}

		return inSampleSize;
	}

	public static Bitmap decodeSampledBitmapFromResource(Resources resources,
			int resId, int reqW, int reqH) {

		Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(resources, resId);

		options.inSampleSize = calculateInSampleSize(options, reqW, reqH);

		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeResource(resources, resId, options);
	}

	public static Bitmap decodeSampledBitmapFromFileImagePath(
			String fileImagePath, int reqW, int reqH) {

		Options options = new Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(fileImagePath, options);

		options.inSampleSize = calculateInSampleSize(options, reqW, reqH);

		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(fileImagePath, options);
	}
}
